package com.example.houseitemmanagebackend.controller;

import com.example.houseitemmanagebackend.entity.Category;
import com.example.houseitemmanagebackend.security.JwtUserDetails;
import com.example.houseitemmanagebackend.service.CategoryService;
import com.example.houseitemmanagebackend.vo.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 分类管理控制器
 */
@Tag(name = "分类管理", description = "物品分类管理相关接口")
@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Operation(summary = "获取分类列表", description = "获取分类列表接口")
    @GetMapping
    public Result<List<Category>> getCategoryList(@AuthenticationPrincipal JwtUserDetails userDetails) {
        return Result.success(categoryService.getCategoryList(userDetails.getId()));
    }

    @Operation(summary = "添加分类", description = "添加分类接口")
    @PostMapping
    public Result<Map<String, Integer>> addCategory(@RequestBody Map<String, String> params,
            @AuthenticationPrincipal JwtUserDetails userDetails) {
        String name = params.get("name");
        if (name == null || name.trim().isEmpty()) {
            return Result.error(400, "分类名称不能为空");
        }

        Integer categoryId = categoryService.addCategory(name, userDetails.getId());
        return Result.success(Map.of("id", categoryId));
    }

    @Operation(summary = "更新分类", description = "更新分类接口")
    @PutMapping("/{id}")
    public Result<Void> updateCategory(@PathVariable Integer id,
            @RequestBody Map<String, String> params,
            @AuthenticationPrincipal JwtUserDetails userDetails) {
        String name = params.get("name");
        if (name == null || name.trim().isEmpty()) {
            return Result.error(400, "分类名称不能为空");
        }

        categoryService.updateCategory(id, name, userDetails.getId());
        return Result.success();
    }

    @Operation(summary = "删除分类", description = "删除分类接口")
    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@PathVariable Integer id,
            @AuthenticationPrincipal JwtUserDetails userDetails) {
        categoryService.deleteCategory(id, userDetails.getId());
        return Result.success();
    }
}